package me.fangjian.antunet.lib;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class Tunet extends Thread{

	private byte[] welcome = new byte[8];
	private String main_server = "166.111.8.10";
	private int main_server_port = 80;
	private byte[] keepalive_key = new byte[8];
	private String keepalive_server;
	private int keepalive_server_port = 0;
	private Tick keepalive_timeout;
	private String mesg_server;
	private int mesg_server_port;
	private Tunet_State state = Tunet_State.TUNET_STATE_NONE;
	private UserConfig uc;
	private SocketChannel main_socket;
	private SocketChannel keepalive_socket;
	private SocketChannel logout_socket;
	private Buffer main_socket_buffer;
	private Buffer keepalive_socket_buffer;
	private Buffer logout_socket_buffer;

	private void tunet_connect_main_server() throws IOException,
			InterruptedException {
		main_socket = Tunet.createSocketChannel(main_server, main_server_port,
				false);
	}

	private void tunet_connect_keepalive_server() throws IOException,
			InterruptedException {
		keepalive_socket = Tunet.createSocketChannel(keepalive_server,
				keepalive_server_port, false);
	}

	private void tunet_connect_logout_server() throws IOException,
			InterruptedException {
		logout_socket = Tunet.createSocketChannel(main_server,
				main_server_port, false);
	}

	public static SocketChannel createSocketChannel(String hostName, int port,
			boolean block) throws IOException, InterruptedException {
		// Create a non-blocking socket channel
		SocketChannel sChannel = SocketChannel.open();
		sChannel.configureBlocking(block);

		// Send a connection request to the server; this method is non-blocking
		sChannel.connect(new InetSocketAddress(hostName, port));
		while (!sChannel.finishConnect()) {
			Thread.sleep(100);
		}
		return sChannel;
	}

	public void tunet_stop() {

	}

	public boolean tunet_is_keepalive_timeout() {
		return false;

	}

	public void tunet_start() {

	}

	public void tunet_reset() {

	}

	public int tunet_get_state() {
		return 0;

	}

	public void tunet_init() {

	}

	public void tunet_cleanup() {

	}
	
	@Override
	public void run(){
		boolean hasErr = false;
		while(!hasErr){
				try {
					if(state == Tunet_State.TUNET_STATE_LOGIN)
						tunet_connect_main_server();
					tunet_connect_keepalive_server();
				} catch (IOException e) {
					hasErr = true;
					e.printStackTrace();
				} catch (InterruptedException e) {
					hasErr = true;
					e.printStackTrace();
				}
		}
	}
}
